String.prototype.replaceArray = function(find, replace) {
  var replaceString = this;
  var regex; 
  for (var i = 0; i < find.length; i++) {
    regex = new RegExp(find[i], "g");
    replaceString = replaceString.replace(regex, replace[i]);
  }
  return replaceString;
};


jQuery.cors = true;

var base_url = "http://swe.cmpe.boun.edu.tr:8280";
var mylat = 0;
var mylon = 0;
var tmp_lat = 0;
var tmp_lon = 0;
var search_tag_list = "";
var search_user = "";
var importanceStart = "0";
var importanceEnd = "10000";
var tmp_tag_list = "";
var tmp_user = "";

var location_list = null;
var tag_list = null;

var db_addr = {
	handicap_type: "{base_url}/arceone/rest/getHandicapTypes/1"
	,tag: "{base_url}/arceone/rest/getTagsByLevel/2"
	,tagByLevel: "{base_url}/arceone/rest/getTagsByLevel/{id}"
	,tagByParentId: "{base_url}/arceone/rest/getTagsByParentId/{id}"
	,user:"{base_url}/arceone/rest/getUserInfo/{uid}"
	,violation_report: "{base_url}/arceone/violation/violations/report"
	,violation_abuse: "{base_url}/arceone/violation/violations/reportAbuse"
	,violation_resolve: "{base_url}/arceone/violation/violations/resolveMobile"
	,violation_add: "{base_url}/arceone/violation/violations/addMobile"
	,violation_unfollow: "{base_url}/arceone/violation/violations/unFollowMobile"
	,violation_follow: "{base_url}/arceone/violation/violations/followMobile"
	,violation_object: "{base_url}/arceone/rest/getViolation/{id}"
	,search_violation: "{base_url}/arceone/rest/searchViolations/{user}&{handicap}&{limitStart}-{limitEnd}&{timeStart}-{timeEnd}&{importanceStart}-{importanceEnd}&{topLeftX}-{topLeftY}&{bottomRightX}-{bottomRightY}"
	,login: "{base_url}/arceone/j_spring_security_check"
	,logout: "{base_url}/arceone/j_spring_security_logout"
	,session: "{base_url}/arceone/rest/getUserInfo/0"
	,isadmin: "{base_url}/arceone/rest/getUserInfo/2"
	,register: "{base_url}/arceone/processRegistration"
	,g: function(tmpl){
		return tmpl.replace("{base_url}",base_url);
	}
};
var app = $.sammy('#main', function() {
		
		  this.use('Template');

		   function checkLoggedIn(callback) {
		     // /session returns a JSON representation of the logged in user
		     // or an empty object
		     if (!appViewModel.my()) {
		       $.get(db_addr.g(db_addr.session), function(json) {
		         if (json.length>0) {
		           // show the user as logged in
		           $.get(db_addr.g(db_addr.user.replace("{uid}",json[0].id)),function(d){
		           				d[0].profileImage = gravatar(d[0].email);
	          					appViewModel.my(d[0]);
	          					appViewModel.loggedin(true);
	          					appViewModel.followedViolations(d[0].followedViolations);
	          					appViewModel.isAdmin(d[0].admin);
          			});
		           // execute the route path
		           callback();
		         } else {
		           // show the user as not logged in
		           appViewModel.my(null);
		           appViewModel.loggedin(false);
		           appViewModel.followedViolations([]);
		           // the context of aroundFilters is an EventContext
		           //this.redirect('#/');
		           callback();
		         }
		       });
		     } else {
		       // execute the route path
		       callback();
		     }
		   };

		   this.around(checkLoggedIn);




      
          this.get('#/', function(context) {
          	appViewModel.current("home");
			var item_id = "";
          	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
			  $("#main").show();
			  $("#harita").hide();
			  context.app.swap('');
				this.load(db_addr.g(db_addr.search_violation).replaceArray(["{user}","{handicap}","{limitStart}","{limitEnd}","{timeStart}-{timeEnd}","{importanceStart}","{importanceEnd}","{topLeftX}","{topLeftY}","{bottomRightX}","{bottomRightY}"],["",search_tag_list,0,100,"",importanceStart,importanceEnd,mylat-0.1,mylon+0.1,mylat+0.1,mylon-0.1]),{cache: false})
				.then(function(items){
					var item_obj = JSON.parse(items);
					$.each(item_obj, function(i, x) {
						 if(!isFollowedOne(x.id)){
						  context.render("template/violation.template", {item: x,isFollowed:false,"isLogin":appViewModel.loggedin(),"isAdmin": appViewModel.isAdmin()},{cache: false}).appendTo(context.$element());
						} else{
						  context.render("template/violation.template", {item: x,isFollowed:true,"isLogin":appViewModel.loggedin(),"isAdmin": appViewModel.isAdmin()},{cache: false}).appendTo(context.$element());
						} 
					});
				}).then(function(){
					setTimeout(
						function(){
							$('.violation_reports').wookmark({
						  		container: $('#main'),
						  		offset: 10,
						  		itemWidth: $('.violation_reports:first').width(),
						  		autoResize: true
							});
					}, 750);
				});
          });
		  this.get('#/arama', function(context) {
		  	$(".form-search").submit(function(){return false;});
		  	appViewModel.previousPage = appViewModel.current();
          	appViewModel.current("arama");
          	$("#search").unbind("keyup").keyup(function(){
          		$("#autocomplete_area").html("");
          		var search_varibles = $("#search").val().split(",");
          		if(search_varibles.length>0){
	          		if(search_varibles[search_varibles.length-1].substring(0,1)=="@" && location_list != null){
	          			$.each(location_list,function(i,item){
	          				if(item.title.search(search_varibles[search_varibles.length-1].substring(1))>0){	
	          					$("#autocomplete_area").append('<li><div onclick="search_query_prepare(\'@\',\''+item.title+'\')">'+item.title+'</div></li>');
	          					if($("#autocomplete_area li").size()>0)
	          						appViewModel.autocomplete(true);
	          					else
	          						appViewModel.autocomplete(false);
	          				}
	          			});
	          		}
	          		if(search_varibles[search_varibles.length-1].substring(0,1)=="#" && location_list != null){
	          			$.each(tag_list,function(i,item){
	          				if(item.title.search(search_varibles[search_varibles.length-1].substring(1))>0){	
	          					$("#autocomplete_area").append('<li><div onclick="search_query_prepare(\'#\',\''+item.title+'\')">'+item.title+'</div></li>');
	          					if($("#autocomplete_area li").size()>0)
	          						appViewModel.autocomplete(true);
	          					else
	          						appViewModel.autocomplete(false);
	          				}
	          			});
	          		}
          		} else {
          			appViewModel.autocomplete(false);
          		}
          	});
          	$("#search_submit").click(function(){
          		search_tag_list = "";
          		if(tmp_lat != 0 && tmp_lon != 0){
          			mylat = tmp_lat;
          			mylon = tmp_lon;
          		}
          		var search_varibles = $("#search").val().split(",");
          		$.each(search_varibles,function(i,item){
          			if(item.substring(0,1) == "@"){	
          				if(search_tag_list == ""){
          					search_tag_list += item.substring(1)
          				} else {
          					search_tag_list += "-"+item.substring(1)
          				}
          			}
          			if(item.substring(0,1) == "#"){	
          				if(search_tag_list == ""){
          					search_tag_list += item.substring(1)
          				} else {
          					search_tag_list += "-"+item.substring(1)
          				}
          			}
          			if(item.substring(0,1) == ":"){	
          				
          			}
          			if(item.substring(0,1) == "!"){	
          				if(search_tag_list == ""){
          					if(item.substring(1) == "düşük"){
          						importanceStart = 0;
          						importanceEnd = 20;
          					}
          					if(item.substring(1) == "orta"){
          						importanceStart = 20;
          						importanceEnd = 40;
          					}
          					if(item.substring(1) == "yüksek"){
          						importanceStart = 40;
          						importanceEnd = 60;
          					}
          					if(item.substring(1) == "çok yüksek"){
          						importanceStart = 60;
          						importanceEnd = 100000000;
          					}
          				} else {
          					importanceStart = 0;
          						importanceEnd = 20;
          				}
          			}

          			if(appViewModel.previousPage == "home" || appViewModel.previousPage == "harita" || appViewModel.previousPage == "tablo"){
          				if(history.state){history.go(-1);} else {app.setLocation("#/");}
          			} else{
          				app.setLocation("#/");
          			}


          		});
          	});
			$("#search_cancel").unbind("click").click(function(){
				tmp_lat = 0;
				tmp_lon = 0;
				search_tag_list = "";
				search_user = "";
				importanceStart = "0";
				importanceEnd = "10000";
				tmp_tag_list = "";
				tmp_user = "";

				location_list = null;
				tag_list = null;
				navigator.geolocation.getCurrentPosition(function(position) {
			    	mylat = position.coords.latitude;
			    	mylon = position.coords.longitude;
			    });
				if(appViewModel.previousPage == "home" || appViewModel.previousPage == "harita" || appViewModel.previousPage == "tablo"){
          				if(history.state){history.go(-1);} else {app.setLocation("#/");}
          			} else{
          				app.setLocation("#/");
          			}
			});
          	map.initsearch($(".saerch_item_holder"));
			
          });
		  this.get('#/tablo', function(context) {
          	appViewModel.current("tablo");
          	var self = this;
          	setTimeout(function(){
	          	if(appViewModel.isAdmin()){
					var item_id = "";
		          	$("#modal_with_content").modal('hide');
		          	$("#modal_with_action").modal('hide');
					  $("#main").show();
					  $("#harita").hide();
					  context.app.swap('');
						self.load(db_addr.g(db_addr.search_violation).replaceArray(["{user}","{handicap}","{limitStart}","{limitEnd}","{timeStart}-{timeEnd}","{importanceStart}","{importanceEnd}","{topLeftX}","{topLeftY}","{bottomRightX}","{bottomRightY}"],["",search_tag_list,0,100,"",importanceStart,importanceEnd,mylat-0.1,mylon+0.1,mylat+0.1,mylon-0.1]),{cache: false})
						.then(function(items){
							var item_obj = JSON.parse(items);
							context.$element().html('<table class="table table-striped table-bordered"></table>');
							$.each(item_obj, function(i, x) {
								 if(!isFollowedOne(x.id)){
								  context.render("template/violation_table.template", {item: x,isFollowed:false,"isLogin":appViewModel.loggedin(),"isAdmin": appViewModel.isAdmin()},{cache: false}).appendTo(context.$element().find(".table"));
								} else{
								  context.render("template/violation_table.template", {item: x,isFollowed:true,"isLogin":appViewModel.loggedin(),"isAdmin": appViewModel.isAdmin()},{cache: false}).appendTo(context.$element().find(".table"));
								} 
							});
						});
	          	}
          	},500);
          
          });
		  this.get('#/pop/:id', function(context) {
		  	appViewModel.current("pop");
			var item_id = this.params['id'];
          	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#main").show();
			$("#harita").hide();
          	context.app.swap('');
				this.load(db_addr.g(db_addr.violation_object).replace("{id}",item_id),{cache: false})
				.then(function(items){
					//$.each(items, function(i, x) {
						//if(x.id == item_id){
						  $("#lb_content").html("");
						  if(!isFollowedOne(item_id))
						  	context.render("template/violation_pop.template", {item: JSON.parse(items)[0],isFollowed:false,"isLogin":appViewModel.loggedin(),"isAdmin": appViewModel.isAdmin()},{cache: false}).appendTo($("#main"));
						  else
						  	context.render("template/violation_pop.template", {item: JSON.parse(items)[0],isFollowed:true,"isLogin":appViewModel.loggedin(),"isAdmin": appViewModel.isAdmin()},{cache: false}).appendTo($("#main"));
						//}
					//});
				}).then(function(items){
					setTimeout(function(){$(".comments_holder, .comments_holder .comments").css("min-height",($(window).height()-50)+"px");$(".violation_report .well").css("min-height",($(window).height()-88)+"px");
						$.each(JSON.parse(items)[0].reports,function(i,x){
							x.user.email = gravatar(x.user.email);
							if(x.description!=null && !x.firstReport)
							context.render("template/violation_report.template", {item: x},{cache: false}).appendTo($("#main .comments_holder .comments"));
						});
					},200);
				});
          });
		  this.get('#/harita/:id', function(context) {
		  	appViewModel.current("harita");
           	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
			var item_id = this.params['id'];
			lastLocation = '#/harita/'+item_id;
			context.app.swap('');
			$("#main").hide();
			$("#harita").show();
			map.init();
			this.load(db_addr.g(db_addr.violation_object).replace("{id}",item_id),{cache: false})
				.then(function(items){
					var item_obj = JSON.parse(items);
					$.each(item_obj, function(i, x) {
						map.addImage(x.location.lattitude,x.location.longtitude,x.proofs[0].url,item_id);
					});
				});
          });
          this.get('#/harita', function(context) {
          	appViewModel.current("harita");
           	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
			var item_id = this.params['id'];
			lastLocation = '#/harita';
			context.app.swap('');
			$("#main").hide();
			$("#harita").show();
			map.init();
			this.load(db_addr.g(db_addr.search_violation).replaceArray(["{user}","{handicap}","{limitStart}","{limitEnd}","{timeStart}-{timeEnd}","{importanceStart}","{importanceEnd}","{topLeftX}","{topLeftY}","{bottomRightX}","{bottomRightY}"],["",search_tag_list,0,100,"",importanceStart,importanceEnd,mylat-0.1,mylon+0.1,mylat+0.1,mylon-0.1]),{cache: false})
				.then(function(items){
					var item_obj = JSON.parse(items);
					$.each(item_obj, function(i, x) {
						map.addImage(x.location.lattitude,x.location.longtitude,(x.proofs.length>0)?x.proofs[0].url:"http://placehold.it/300&text=imaj yok",x.id);
					});
				});
          });
          this.get('#/login',function(context){
          	appViewModel.current("login");
          	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#modal_with_action .modal-body").html("");
          	context.render("template/login_pop.template").appendTo($("#modal_with_action .modal-body"));
          	$("#modal_with_action #ModalLabel").html("Üye Girişi");
          	$("#modal_with_action").modal('show');
          	$("#modal_with_action").on('shown',function(){
	          	$("#modal_with_action .submit").unbind("click").bind("click",function(){
	          		$.post(db_addr.g(db_addr.login)
	          			,{
	          				 "j_username": $("#modal_with_action form .username").val()
	          				,"j_password": $("#modal_with_action form .password").val()
	          			}
	          			,function(data){
		          			if(data[0].id > 0){
	          					$("#modal_with_action").modal('hide');
	          					$.get(db_addr.g(db_addr.user.replace("{uid}",data[0].id)),function(d){
	          						d[0].profileImage = gravatar(d[0].email);
		          					appViewModel.my(d[0]);
		          					appViewModel.loggedin(true);
		          					appViewModel.followedViolations(d[0].followedViolations);
	          					});
		          			} else {
		          					$("#modal_with_action .modal-body")
		          					.prepend('<div class="alert alert-block alert-error fade in"><button type="button" class="close" data-dismiss="alert">×</button><p>Bilgileriniz hatalı!</p>')
		          					.find('.alert')
		          					.alert()
		          					.bind("closed",function(){$(".alert").remove();});
		          			}
	          			});
					setTimeout(function(){app.setLocation("#/");},500);
	          	});
          	});
          	$("#modal_with_action").on('hidden',function(){if(history.state){history.go(-1);} else {app.setLocation("#/");}});
          });
          this.get('#/logout',function(context){
          	appViewModel.current("logout");
          		$.post(db_addr.g(db_addr.logout),function(){
          			appViewModel.my(null);
          			appViewModel.loggedin(false);
          			appViewModel.followedViolations([]);
          			appViewModel.isAdmin(false);
          			if(history.state){history.go(-1);} else {app.setLocation("#/");}
          		});
          });
          this.get("#/kayit",function(context){
          	appViewModel.current("kayit");
          	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#modal_with_action .modal-body").html("");
          	context.render("template/register_pop.template").appendTo($("#modal_with_action .modal-body"));
          	$("#modal_with_action #ModalLabel").html("Üye Kayıt");
          	$("#modal_with_action").modal('show');
          	$("#modal_with_action").on("shown",function(){
          		$("#handicapTypes").html("");
          		$.get(db_addr.g(db_addr.handicap_type),function(data){
          			$.each(data,function(i,item){
          				$("#handicapTypes").append('<option value="'+item.id+'">'+item.title+'</option>');
          			});
          		});
          		$("#modal_with_action #profil_photo").popover({title:"Kullanıcı adı",html:true,content:'<span class="label">Yeni üye</span> <span class="badge">0</span> bildiri <span class="badge">0</span> yorum'});
          		$("#email").blur(function(){
          			$("#modal_with_action #profil_photo").attr("src",gravatar($("#email").val()));
          		});
          		$("#username").blur(function(){
          			$("#modal_with_action #profil_photo").popover("destroy");
          			$("#modal_with_action #profil_photo").popover({title:$("#username").val(),html:true,content:'<span class="label">Yeni üye</span> <span class="badge">0</span> bildiri <span class="badge">0</span> yorum'});
          		});
          		$("#modal_with_action button.submit").unbind("click").bind("click",function(){
          			$.post(db_addr.g(db_addr.register),$("#modal_with_action form").serialize(),function(data){
          				//$("#modal_with_action").hide();
          				setTimeout(function(){app.setLocation("#/login");}, 200);
          			});
          		});
          	});
          	$("#modal_with_action").on('hidden',function(){if(history.state){history.go(-1);} else {app.setLocation("#/");}});
          });
		  this.get("#/problem_bildir",function(context){
		  	appViewModel.current("problem_bildir");
		  	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#modal_with_action .modal-body").html('');
          	context.render("template/violation_form.template",{"username":appViewModel.my().userName},{cache:false}).appendTo($("#modal_with_action .modal-body"));
          	$("#modal_with_action #ModalLabel").html("Problem Bildir");
          	$("#modal_with_action").modal("show");
          	$("#modal_with_action").on('hidden',function(){if(history.state){history.go(-1);} else {app.setLocation("#/");}});
          	$("#modal_with_action").on("shown",function(){
          		map.initmini($("#violation_report_form"));
          		$("#tagIdString").html('');
          		$.get(db_addr.g(db_addr.tag),function(data){
          			$.each(data,function(i,item){
          				if(i==0)
          					$("#tagIdString").append('<option value="'+item.id+'" selected="selected">'+item.title+'</option>');
          				else
          					$("#tagIdString").append('<option value="'+item.id+'">'+item.title+'</option>');
          			});
          			$("#tagId2String").html('');
      				var selfObj = $("#tagIdString");
      				$.get(db_addr.g(db_addr.tagByParentId).replace("{id}",selfObj.val()),function(data){
      					if(data.length > 0){
      						$.each(data,function(i,item){
		          				if(i==0)
		          					$("#tagId2String").append('<option value="'+item.id+'" selected="selected">'+item.title+'</option>');
		          				else
		          					$("#tagId2String").append('<option value="'+item.id+'">'+item.title+'</option>');
		          			});
      						$("#extra_list_1").show();
      					} else {
      						$("#tagId2String").html('<option value="-1" selected="selected"></option>');
      						$("#extra_list_1").hide();
      					}
      				});
          			$("#tagIdString").change(function(){
          				$("#tagId2String").html('');
          				$("#tagId3String").html('');
          				$("#extra_list_1").hide();
			          	$("#extra_list_2").hide();
          				var self = $(this);
          				$.get(db_addr.g(db_addr.tagByParentId).replace("{id}",self.val()),function(data2){
          					if(data2.length > 0){
          						$.each(data2,function(i,item2){
          							if(i==0)
			          					$("#tagId2String").append('<option value="'+item2.id+'" selected="selected">'+item2.title+'</option>');
          							else
			          					$("#tagId2String").append('<option value="'+item2.id+'">'+item2.title+'</option>');
			          			});
			          			$("#extra_list_1").show();
			          			var selfObj = $("#tagId2String");
			          			$("#tagId3String").html('');
			      				$.get(db_addr.g(db_addr.tagByParentId).replace("{id}",selfObj.val()),function(datax){
			      					if(datax.length > 0){
			      						$.each(datax,function(i,itemx){
					          				if(i==0)
					          					$("#tagId3String").append('<option value="'+itemx.id+'" selected="selected">'+itemx.title+'</option>');
					          				else
					          					$("#tagId3String").append('<option value="'+itemx.id+'">'+itemx.title+'</option>');
					          			});
			      						$("#extra_list_2").show();
			      					} else {
			      						$("#tagId3String").html('');
			      						$("#extra_list_2").hide();
			      					}
			      				});
			          			$("#tagId2String").change(function(){
			          				$("#tagId3String").html('');
			          				$("#extra_list_2").hide();
			          				var self2 = $(this);
			          				$.get(db_addr.g(db_addr.tagByParentId).replace("{id}",self2.val()),function(data3){
			          					if(data3.length > 0){
			          						$.each(data3,function(i,item3){
						          				if(i==0)
						          					$("#tagId3String").append('<option value="'+item3.id+'" selected="selected">'+item3.title+'</option>');
						          				else
						          					$("#tagId3String").append('<option value="'+item3.id+'">'+item3.title+'</option>');
						          			});
			          						$("#extra_list_2").show();
			          					} else {
			          						$("#tagId3String").html('<option value="-1" selected="selected"></option>');
			          						$("#extra_list_2").hide();
			          					}
			          				});
			          			});
          					} else {
          						$("#tagId2String").html('<option value="-1" selected="selected"></option>');
          						$("#tagId3String").html('');
			          			$("#extra_list_1").hide();
			          			$("#extra_list_2").hide();
          					}
          				});
          			});
          		})
          		$("#modal_with_action button.submit").unbind("click").bind("click",function(){
          			if($("#lon").val() != "" && $("#lat").val() != ""){
          				$(".make_tr_fix").each(function(){
          					var str = $(this).val();
          					//str = str.replaceArray(["ı","ç","ğ","ş","ö","ü","İ","Ç","Ğ","Ş","Ö","Ü"],["&#305;","&ccedil;","&#287;","&#351;","&ouml;","&uuml;","&#30;","&Ccedil;","&#286;","&#350;","&Ouml;","&Uuml;"]);
          					str = str.replaceArray(["İ","Ç","Ğ","Ş","Ö","Ü"],["I","C","G","S","O","U"]);
          					$(this).val(str);
          				});
          				$("#ilce").val($("#ilce").val().replaceArray(["ı","ç","ğ","ş","ö","ü","İ","Ç","Ğ","Ş","Ö","Ü"],["i","c","g","s","o","u","I","C","G","S","O","U"]));
          				$("#ilce").val($("#ilce").val().toLowerCase());
          				setTimeout(function(){
		          			var formData = new FormData($("#modal_with_action form")[0]);
						    $.ajax({
						        url: db_addr.g(db_addr.violation_add),  //server script to process data
						        type: 'POST',
						        xhr: function() {  // custom xhr
						            myXhr = $.ajaxSettings.xhr();
						            if(myXhr.upload){ // check if upload property exists
						            	$(".progress").remove();
						            	$("#file").after('<div class="progress"><div class="bar" style="width: 0%;"></div></div>');
						                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
						            }
						            return myXhr;
						        },
						        //Ajax events
						        beforeSend: "",
						        success: function(){$("#modal_with_action").modal("hide");},
						        error: "",
						        // Form data
						        data: formData,
						        //Options to tell JQuery not to process data or worry about content-type
						        cache: false,
						        contentType: false,
						        processData: false
						    });
          				},500);
          			}
          		});
          	});
		  });
		  this.get("#/raporla/:id",function(context){
		  	var item_id = this.params['id'];
		  	appViewModel.current("problem_bildir");
		  	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#modal_with_action .modal-body").html('');
          	context.render("template/violation_report_form.template",{"username":appViewModel.my().userName,"id":item_id},{cache:false}).appendTo($("#modal_with_action .modal-body"));
          	$("#modal_with_action #ModalLabel").html("Raporlayın");
          	$("#modal_with_action").modal("show");
          	$("#modal_with_action").on('hidden',function(){if(history.state){history.go(-1);} else {app.setLocation("#/");}});
          	$("#modal_with_action").on("shown",function(){
          		$("#modal_with_action button.submit").unbind("click").bind("click",function(){
          			if($("#lon").val() != "" && $("#lat").val() != ""){
          				$(".make_tr_fix").each(function(){
          					var str = $(this).val();
          					//str = str.replaceArray(["ı","ç","ğ","ş","ö","ü","İ","Ç","Ğ","Ş","Ö","Ü"],["&#305;","&ccedil;","&#287;","&#351;","&ouml;","&uuml;","&#30;","&Ccedil;","&#286;","&#350;","&Ouml;","&Uuml;"]);
          					str = str.replaceArray(["İ","Ç","Ğ","Ş","Ö","Ü"],["I","C","G","S","O","U"]);
          					$(this).val(str);
          				});
          				setTimeout(function(){
		          			var formData = new FormData($("#modal_with_action form")[0]);
						    $.ajax({
						        url: db_addr.g(db_addr.violation_report),  //server script to process data
						        type: 'POST',
						        xhr: function() {  // custom xhr
						            myXhr = $.ajaxSettings.xhr();
						            if(myXhr.upload){ // check if upload property exists
						            	$(".progress").remove();
						            	$("#file").after('<div class="progress"><div class="bar" style="width: 0%;"></div></div>');
						                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
						            }
						            return myXhr;
						        },
						        //Ajax events
						        beforeSend: "",
						        success: function(){$("#modal_with_action").modal("hide");},
						        error: "",
						        // Form data
						        data: formData,
						        //Options to tell JQuery not to process data or worry about content-type
						        cache: false,
						        contentType: false,
						        processData: false
						    });
          				},500);
          			}
          		});
          	});
		  });
		  this.get("#/kotuyekullanimbildir/:id",function(context){
		  	var item_id = this.params['id'];
		  	appViewModel.current("problem_bildir");
		  	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#modal_with_action .modal-body").html('');
          	context.render("template/violation_report_form.template",{"username":appViewModel.my().userName,"id":item_id},{cache:false}).appendTo($("#modal_with_action .modal-body"));
          	$("#modal_with_action #ModalLabel").html("Kötüye Kullanımı Bildirin");
          	$("#modal_with_action").modal("show");
          	$("#modal_with_action").on('hidden',function(){if(history.state){history.go(-1);} else {app.setLocation("#/");}});
          	$("#modal_with_action").on("shown",function(){
          		$("#modal_with_action button.submit").unbind("click").bind("click",function(){
          			if($("#lon").val() != "" && $("#lat").val() != ""){
          				$(".make_tr_fix").each(function(){
          					var str = $(this).val();
          					//str = str.replaceArray(["ı","ç","ğ","ş","ö","ü","İ","Ç","Ğ","Ş","Ö","Ü"],["&#305;","&ccedil;","&#287;","&#351;","&ouml;","&uuml;","&#30;","&Ccedil;","&#286;","&#350;","&Ouml;","&Uuml;"]);
          					str = str.replaceArray(["İ","Ç","Ğ","Ş","Ö","Ü"],["I","C","G","S","O","U"]);
          					$(this).val(str);
          				});
          				setTimeout(function(){
		          			var formData = new FormData($("#modal_with_action form")[0]);
						    $.ajax({
						        url: db_addr.g(db_addr.violation_abuse),  //server script to process data
						        type: 'POST',
						        xhr: function() {  // custom xhr
						            myXhr = $.ajaxSettings.xhr();
						            if(myXhr.upload){ // check if upload property exists
						            	$(".progress").remove();
						            	$("#file").after('<div class="progress"><div class="bar" style="width: 0%;"></div></div>');
						                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
						            }
						            return myXhr;
						        },
						        //Ajax events
						        beforeSend: "",
						        success: function(){$("#modal_with_action").modal("hide");},
						        error: "",
						        // Form data
						        data: formData,
						        //Options to tell JQuery not to process data or worry about content-type
						        cache: false,
						        contentType: false,
						        processData: false
						    });
          				},500);
          			}
          		});
          	});
		  });
		  this.get("#/cozumle/:id",function(context){
		  	var item_id = this.params['id'];
		  	appViewModel.current("problem_bildir");
		  	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#modal_with_action .modal-body").html('');
          	context.render("template/violation_report_form.template",{"username":appViewModel.my().userName,"id":item_id},{cache:false}).appendTo($("#modal_with_action .modal-body"));
          	$("#modal_with_action #ModalLabel").html("Çözümleyin");
          	$("#modal_with_action").modal("show");
          	$("#modal_with_action").on('hidden',function(){if(history.state){history.go(-1);} else {app.setLocation("#/");}});
          	$("#modal_with_action").on("shown",function(){
          		$("#modal_with_action button.submit").unbind("click").bind("click",function(){
          			if($("#lon").val() != "" && $("#lat").val() != ""){
          				$(".make_tr_fix").each(function(){
          					var str = $(this).val();
          					//str = str.replaceArray(["ı","ç","ğ","ş","ö","ü","İ","Ç","Ğ","Ş","Ö","Ü"],["&#305;","&ccedil;","&#287;","&#351;","&ouml;","&uuml;","&#30;","&Ccedil;","&#286;","&#350;","&Ouml;","&Uuml;"]);
          					str = str.replaceArray(["İ","Ç","Ğ","Ş","Ö","Ü"],["I","C","G","S","O","U"]);
          					$(this).val(str);
          				});
          				setTimeout(function(){
		          			var formData = new FormData($("#modal_with_action form")[0]);
						    $.ajax({
						        url: db_addr.g(db_addr.violation_resolve),  //server script to process data
						        type: 'POST',
						        xhr: function() {  // custom xhr
						            myXhr = $.ajaxSettings.xhr();
						            if(myXhr.upload){ // check if upload property exists
						            	$(".progress").remove();
						            	$("#file").after('<div class="progress"><div class="bar" style="width: 0%;"></div></div>');
						                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
						            }
						            return myXhr;
						        },
						        //Ajax events
						        beforeSend: "",
						        success: function(){$("#modal_with_action").modal("hide");},
						        error: "",
						        // Form data
						        data: formData,
						        //Options to tell JQuery not to process data or worry about content-type
						        cache: false,
						        contentType: false,
						        processData: false
						    });
          				},500);
          			}
          		});
          	});
		  });
		  this.get("#/profilim",function(context){
		  	appViewModel.current("profilim");
		  	$("#modal_with_content").modal('hide');
          	$("#modal_with_action").modal('hide');
          	$("#modal_with_action .modal-body").html('');
          	context.render("template/myprofile.template",{"item":appViewModel.my()},{cache: false}).appendTo($("#modal_with_action .modal-body"));
          	$("#modal_with_action #ModalLabel").html("Profilim");
          	$("#modal_with_action").modal("show");
          	$("#modal_with_action").on('hidden',function(){if(history.state){history.go(-1);} else {app.setLocation("#/");}});
          	$("#modal_with_action").on("shown",function(){
          		
          	});
		  });
      
        });
//maps
var map = {
	obj : null,
	init: function(lat,lon){
		var mapOptions = {
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.HYBRID
        };
        if($(window).width() < 768){
        	$("#harita").height(($(window).height()-108 > 250)?$(window).height()-108:250);
        } else {
			$("#harita").height(($(window).height()-42 > 250)?$(window).height()-42:250);
		}
		$(window).resize(function(){
			if($(window).width() <768){
	        	$("#harita").height(($(window).height()-108 > 250)?$(window).height()-108:250);
	        } else {
				$("#harita").height(($(window).height()-42 > 250)?$(window).height()-42:250);
			}
		});
        map.obj = new google.maps.Map(document.getElementById('harita'),
            mapOptions);

        // Try HTML5 geolocation
        if(navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);


            map.obj.setCenter(pos);
          });
        } else {
          // Browser doesn't support Geolocation
		  var pos = new google.maps.LatLng(lat, lon);


            map.obj.setCenter(pos);
        }
	},
	initmini : function(container_obj){
		var mapOptions = {
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.HYBRID
        };
        $("#mini_map").height(200);
        $("#mini_map").width(520);
        map.obj = new google.maps.Map(document.getElementById('mini_map'),
            mapOptions);

        // Try HTML5 geolocation
        if(navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);


            map.obj.setCenter(pos);
          });
        } else {
          // Browser doesn't support Geolocation
		  var pos = new google.maps.LatLng(lat, lon);
            map.obj.setCenter(pos);
        }

        google.maps.event.addListener(map.obj, 'click', function(data) {
        	container_obj.find("#lat").val(data.latLng.Za);
        	container_obj.find("#lon").val(data.latLng.$a);
          $.getJSON("http://maps.googleapis.com/maps/api/geocode/json",{"latlng": data.latLng.Za+","+data.latLng.$a , "sensor":false},function(data2){
          	console.log(data2.results[0].address_components);
          	var ilce = null;
          	$.each(data2.results[0].address_components,function(i,adres_part){
          		if(adres_part.types[0]="sublocality" && i <4){
          			ilce = adres_part.long_name;
          		}
          	});
        	container_obj.find("#ilce").val(ilce);
        	container_obj.find("#adress_preview").html(ilce);
          });
        });
	},
	initsearch : function(container_obj){
		$("#seaech_address_preview").html("");
		tmp_lat = 0;
		tmp_lon = 0;
        var pos = new google.maps.LatLng(mylat, mylon);
		var mapOptions = {
          zoom: 15,
          mapTypeId: google.maps.MapTypeId.HYBRID
        };
        $("#search_map").height(150);
        $("#search_map").width($(".search-bg").width()-30);
        map.obj = new google.maps.Map(document.getElementById('search_map'),mapOptions);
        map.obj.setCenter(pos);


        var marker;
        var ico = new google.maps.MarkerImage(base_url+"/img/pin_blue.png",
			new google.maps.Size(64,64),
			new google.maps.Point(0,0),
			new google.maps.Point(32,64),
			new google.maps.Size(64,64)
		);

		function placeMarker(location) {
		  if ( marker ) {
		    marker.setPosition(location);
		  } else {
		    marker = new google.maps.Marker({
		      position: location,
		      map: map.obj,
		      icon: ico
		    });
		  }
		}
		placeMarker(pos);

        google.maps.event.addListener(map.obj, 'click', function(data) {
        	tmp_lat = data.latLng.Za;
        	tmp_lon = data.latLng.$a;
        	pos = new google.maps.LatLng(tmp_lat, tmp_lon);
        	placeMarker(pos);
        	map.obj.panTo(pos);
          $.getJSON("http://maps.googleapis.com/maps/api/geocode/json",{"latlng": data.latLng.Za+","+data.latLng.$a , "sensor":false},function(data2){
        	container_obj.find("#seaech_address_preview").html(data2.results[0].formatted_address);
          });
        });
	},
	addImage: function(lat,lon,image,id){
        var myLatLng = new google.maps.LatLng(lat, lon);
		var ico = new google.maps.MarkerImage(image,
			new google.maps.Size(350,250),
			new google.maps.Point(0,0),
			new google.maps.Point(35,50),
			new google.maps.Size(70,50)
		);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map.obj,
			icon: ico
        });
		google.maps.event.addListener(marker, 'click', function() {
          app.setLocation("#/pop/"+id);
        });
	}
}

$(document).ready(function() {
	ko.applyBindings(appViewModel);
	navigator.geolocation.getCurrentPosition(function(position) {
    	mylat = position.coords.latitude;
    	mylon = position.coords.longitude;
    });
    setTimeout(function(){
    	$(function() {
          app.run('#/');
        });
    },500);
    $("#search").popover();
    tag_list = [];
    var tmp_arr1 = [];
    var tmp_arr2 = [];
    var tmp_arr3 = [];
    location_list = null;
    $.get(db_addr.g(db_addr.tagByLevel).replace("{id}",5),function(data){
    	location_list = data;
    });
    $.get(db_addr.g(db_addr.tagByLevel).replace("{id}",3),function(data){
    	tmp_arr1 = data;
    });
    $.get(db_addr.g(db_addr.tagByLevel).replace("{id}",2),function(data){
    	tmp_arr2 = data;
    });
    $.get(db_addr.g(db_addr.tagByLevel).replace("{id}",1),function(data){
    	tmp_arr3 = data;
    });
    setTimeout(function(){
    	$.each(tmp_arr1,function(i,item){
    		tag_list.push(item);
    	});
    	$.each(tmp_arr2,function(i,item){
    		tag_list.push(item);
    	});
    	$.each(tmp_arr3,function(i,item){
    		tag_list.push(item);
    	});
    },2000);
});

function gravatar(email){
	return "http://www.gravatar.com/avatar/"+CryptoJS.MD5(email.toLowerCase().trim())+"?s=75&d=mm";
}

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('.progress .bar').attr({width:(e.loaded/e.total)+"%"});
    }
}
function follow(id){
	if(appViewModel.my() != null){
		$.post(db_addr.g(db_addr.violation_follow),{userName:appViewModel.my().userName,id:id},function(){
			 $.get(db_addr.g(db_addr.session), function(json) {
		         if (json.length>0) {
		           // show the user as logged in
		           $.get(db_addr.g(db_addr.user.replace("{uid}",json[0].id)),function(d){
		           				d[0].profileImage = gravatar(d[0].email);
	          					appViewModel.my(d[0]);
	          					appViewModel.loggedin(true);
	          					appViewModel.followedViolations(d[0].followedViolations);
	          					$("#violation_"+id+",#violation_pop_"+id).find(".follow").after('<div class="btn btn-mini btn-inverse unfollow" onclick="unfollow('+id+')"><i class="icon-heart icon-white"></i></div>').remove();
	      			});
		           // execute the route path
		         } else {
		           // show the user as not logged in
		           appViewModel.my(null);
		           appViewModel.loggedin(false);
		           appViewModel.followedViolations([]);
		           // the context of aroundFilters is an EventContext
		           //this.redirect('#/');
		         }
		       });
		});
	} else {
		app.setLocation("#/login");
	}
}

function unfollow(id){
	if(appViewModel.my() != null){
		$.post(db_addr.g(db_addr.violation_unfollow),{userName:appViewModel.my().userName,id:id},function(){
			 $.get(db_addr.g(db_addr.session), function(json) {
		         if (json.length>0) {
		           // show the user as logged in
		           $.get(db_addr.g(db_addr.user.replace("{uid}",json[0].id)),function(d){
		           				d[0].profileImage = gravatar(d[0].email);
	          					appViewModel.my(d[0]);
	          					appViewModel.loggedin(true);
	          					appViewModel.followedViolations(d[0].followedViolations);
	          					$("#violation_"+id+",#violation_pop_"+id).find(".unfollow").after('<div class="btn btn-mini follow" onclick="follow('+id+')"><i class="icon-heart"></i></div>').remove();
	      			});
		           // execute the route path
		         } else {
		           // show the user as not logged in
		           appViewModel.my(null);
		           appViewModel.loggedin(false);
		           appViewModel.followedViolations([]);
		           // the context of aroundFilters is an EventContext
		           //this.redirect('#/');
		         }
		       });
		});
	} else {
		app.setLocation("#/login");
	}
}
function isFollowedOne(id){
	if(appViewModel.my() == null){
		return false;
	} else {
		if(appViewModel.my().followedViolations.length > 0){
			var isFollowed = false;
			$.each(appViewModel.my().followedViolations,function(i,item){
				if(item.id == id){
					isFollowed = true;
				}
			});
			return isFollowed;
		} else {
			return false;
		}
	}
}

function search_query_prepare(indicator,str){
	var tmp = "";
	var query_list = $("#search").val().split(",");
	if(query_list.length>0){
		query_list[query_list.length-1] = indicator+str;
		$.each(query_list,function(i,item){
			if(i==0){
				tmp += item;
			} else {
				tmp += ","+item;
			}
		});
		$("#search").val(tmp);
	}
}

var appViewModel = {
	loggedin :  ko.observable(false),
	my : ko.observable(null),
	isAdmin : ko.observable(false),
	current: ko.observable("home"),
	autocomplete: ko.observable(false),
	followedViolations: ko.observableArray([])
}